package apps.softtech.fastmarket;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;
import apps.softtech.Utility.ApplicationConstants;
import apps.softtech.Utility.ConnectionDetector;
import apps.softtech.Utility.HttpRequest;
import apps.softtech.fastmarket.adapter.AdapterPurchasedHistory;
import apps.softtech.fastmarket.adapter.AdapterSaleHistory;
import apps.softtech.fastmarket.model.DatabaseHandler;
import apps.softtech.fastmarket.model.Product;
import apps.softtech.fastmarket.model.SaleTopic;
import apps.softtech.fastmarket.model.UserInfo;

/**
 * 
 * @author MUI
 * 
 */
public class FragmentTabHistory extends Fragment {

	public static final String URL_SALE_PRODUCT = ApplicationConstants.BASE_URL + "product/get_products_completed";
	public static final String URL_BUY_PRODUCT = ApplicationConstants.BASE_URL + "users/get_products_purchased";
	protected static final String TAG = "TAG TAB HISTORY";
	Button btnSale, btnBuy;
	ListView lvSaleHistory, lvBuyHistory;
	ViewFlipper viewFlipper;
	private Animation slide_in_left;
	private Animation slide_out_right;
	private int currentPage;
	private int mUserId;
	SharedPreferences pref;
	ProgressDialog progress;
	AdapterSaleHistory adapterSale;
	AdapterPurchasedHistory adapterPurchase;
	List<SaleTopic> listSaleTopic = new ArrayList<SaleTopic>();
	List<SaleTopic> listPurChased = new ArrayList<SaleTopic>();
	Activity activity;
	ConnectionDetector detector ;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.fragment_history, container, false);
		activity = getActivity();
		detector = new ConnectionDetector(activity);
		init(v);
		pref = getActivity().getSharedPreferences("market_data", 0);
		mUserId = pref.getInt(UserInfo.USERID, -1);
		initViewFlipper();
		setEvent();
		
		/*
		 * check neu co internet thi lay du lieu tu server
		 * neu khong thi lay du lieu trong app de hien thi vao listview
		 */
		
		if(detector.isConnectingToInternet()){
			if(mUserId==-1){
				// neu chua login
				Toast.makeText(activity, "You must Login again", Toast.LENGTH_SHORT).show();
			}
			else{
				// neu da login
				getSaledProductFromServer(ApplicationConstants.RED_ID);
				initListSaleHistory();
			}
		}
		else{
			/*
			 * Neu login vao roi nhung ko co internet
			 */
			getSaledProductInData();
			Log.i(TAG,"size sale: "+ listSaleTopic.size());
			initListSaleHistory();
		}
		
		return v;
	}


	/**
	 * method set event for view in layout
	 */
	private void setEvent() {

		btnSale.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				selectPage(0);

			}
		});

		btnBuy.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				selectPage(1);

			}
		});
	}

	
	/**
	 * select page display in viewFlipper
	 * 
	 * @param page
	 */
	private void selectPage(int page) {

		currentPage = page;
		switch (page) {
		case 0:
			if(detector.isConnectingToInternet() && listSaleTopic.equals(null)){
				getSaledProductFromServer(ApplicationConstants.RED_ID);
				
			}
			else{
				getSaledProductInData();
			}
			
			initListSaleHistory();
			break;
		case 1:
			if(detector.isConnectingToInternet() && listPurChased.equals(null)){
				getPurchaseProductFromServer(ApplicationConstants.RED_ID);
			}
			else{
				getPurchasedProductInData();
			}
			
			initListPurchasedHistory();
			break;
		default:
			break;
		}

		viewFlipper.setDisplayedChild(page);
	}

	/**
	 * init view in this tab
	 * @param v
	 */
	private void init(View v){
		viewFlipper = (ViewFlipper) v.findViewById(R.id.viewFlipper);
		btnSale = (Button) v.findViewById(R.id.btnSaleHistory);
		btnBuy = (Button) v.findViewById(R.id.btnBuyHistory);

		lvSaleHistory = (ListView) v.findViewById(R.id.lvSaleHistory);
		lvBuyHistory = (ListView) v.findViewById(R.id.lvBuyHistory);
	}
	
	/**
	 * init in ViewFlipper
	 */
	private void initViewFlipper() {

		slide_in_left = AnimationUtils.loadAnimation(getActivity(),
				android.R.anim.slide_in_left);
		slide_out_right = AnimationUtils.loadAnimation(getActivity(),
				android.R.anim.slide_out_right);

		viewFlipper.setInAnimation(slide_in_left);
		viewFlipper.setOutAnimation(slide_out_right);
		currentPage = 0;
	}

	/**
	 * init listview purchase product
	 */
	private void initListPurchasedHistory() {
		
		
		adapterPurchase = new AdapterPurchasedHistory(getActivity(),listPurChased);
		
		lvBuyHistory.setAdapter(adapterPurchase);

	}

	/**
	 * init listview sale product
	 */
	private void initListSaleHistory() {
		adapterSale= new AdapterSaleHistory(getActivity(),listSaleTopic);
		
		lvSaleHistory.setAdapter(adapterSale);
	}

	@SuppressWarnings("unchecked")
	private void getSaledProductFromServer(String gcmId) {
		List<NameValuePair> params = new ArrayList<NameValuePair>();

		JSONObject jsonObject = new JSONObject();
		try {
			jsonObject.put("st_GcmId", gcmId);

		} catch (JSONException e) {
			e.printStackTrace();
		}

		params.add(new BasicNameValuePair("data", jsonObject.toString()));

		new AsyncTask<List<NameValuePair>, Void, String>() {

			@Override
			protected void onPreExecute() {
				super.onPreExecute();
			}

			@Override
			protected String doInBackground(List<NameValuePair>... params) {
				HttpRequest request = new HttpRequest();
				String result = request.makeServiceCall(URL_SALE_PRODUCT,
						HttpRequest.POST, params[0]);
				Log.i(TAG, "result get saled product: " + result);
				return result;

			}

			@Override
			protected void onPostExecute(String result) {
				super.onPostExecute(result);

				try {
					JSONObject json = new JSONObject(result);
					if (json.getString("success") != null) {
						int check = json.getInt("success");
						/*
						 * nếu success thi lay data cua server tra ve
						 */
						if (check == 1) {
							Log.i(TAG, "success :1");
							JSONArray jsonData = new JSONArray();
							jsonData = json.getJSONArray("data");
							Toast.makeText(getActivity(), "success",
									Toast.LENGTH_SHORT).show();
							/*
							 * lay data gui ve dua vao listview
							 */
							for(int i=0;i<jsonData.length();i++){
								JSONObject jo = jsonData.getJSONObject(i);
								SaleTopic saleTopic = new SaleTopic();
								saleTopic.setTopic(jo.getString(Product.PRODUCT_NAME));
								saleTopic.setCreatedDate(jo.getString(Product.CREATED_DATE));
								saleTopic.setOfferPrice(Float.parseFloat(jo.getString(Product.PRICE)));
								
								listSaleTopic.add(saleTopic);
							}
							
							if(listSaleTopic.size()>0){
								initListSaleHistory();
							}
						} else {
							Log.i(TAG, "success:0");
						}
					} // } if (json.getString("success") != null)
					
				} catch (JSONException e1) {
					e1.printStackTrace();
				}
			}
		}.execute(params);
	}

	/**
	 * Method to get prouduct user purchased
	 * @param gcmId
	 */
	@SuppressWarnings("unchecked")
	private void getPurchaseProductFromServer(String gcmId) {
		List<NameValuePair> params = new ArrayList<NameValuePair>();

		JSONObject jsonObject = new JSONObject();
		try {
			jsonObject.put("st_GcmId", gcmId);

		} catch (JSONException e) {
			e.printStackTrace();
		}

		params.add(new BasicNameValuePair("data", jsonObject.toString()));

		new AsyncTask<List<NameValuePair>, Void, String>() {

			@Override
			protected void onPreExecute() {
				super.onPreExecute();
			}

			@Override
			protected String doInBackground(List<NameValuePair>... params) {
				HttpRequest request = new HttpRequest();
				String result = request.makeServiceCall(URL_BUY_PRODUCT,
						HttpRequest.POST, params[0]);
				Log.i(TAG, "result get purchase product: " + result);
				return result;

			}

			@Override
			protected void onPostExecute(String result) {
				super.onPostExecute(result);

				try {
					JSONObject json = new JSONObject(result);
					if (json.getString("success") != null) {
						int check = json.getInt("success");
						/*
						 * nếu success thi lay data cua server tra ve
						 */
						if (check == 1) {
							Log.i(TAG, "success :1");
							JSONArray jsonData = new JSONArray();
							jsonData = json.getJSONArray("data");
							Toast.makeText(getActivity(), "success",
									Toast.LENGTH_SHORT).show();
							/*
							 * lay data gui ve dua vao listview
							 */
							for(int i=0;i<jsonData.length();i++){
								JSONObject jo = jsonData.getJSONObject(i);
								SaleTopic saleTopic = new SaleTopic();
								saleTopic.setTopic(jo.getString(Product.PRODUCT_NAME));
								saleTopic.setCreatedDate(jo.getString(Product.CREATED_DATE));
								saleTopic.setOfferPrice(Float.parseFloat(jo.getString(Product.PRICE)));
								
								listPurChased.add(saleTopic);
							}
							
						} else {
							Log.i(TAG, "success:0");
						}
					} // } if (json.getString("success") != null)
					
				} catch (JSONException e1) {
					e1.printStackTrace();
				}
			}
		}.execute(params);
	}
	
	private void saveSaleTopic(){
		DatabaseHandler db = new DatabaseHandler(activity);
		for(int i = 0; i <listSaleTopic.size(); i++){
			SaleTopic saleProduct = listSaleTopic.get(i);
			Product product = new Product();
			product.setProductName(saleProduct.getTopic());
			
			db.insertProduct(product);
		}
	}
	
	/**
	 * get topic saled in data in offline
	 * 
	 */
	private void getSaledProductInData() {
		
		DatabaseHandler db = new DatabaseHandler(getActivity());
		if(db.getSaledProduct(mUserId)!=null){
			listSaleTopic = db.getSaledProduct(mUserId);
		}
		listSaleTopic = db.getSaledProduct(mUserId);
		db.close();
	}
	
	/**
	 * get product purchased in data when offline
	 */
	private void getPurchasedProductInData(){
		
		DatabaseHandler db = new DatabaseHandler(getActivity());
		if(db.getPurchaseProduct(mUserId)!=null){
			listPurChased = db.getSaledProduct(1);
		}
		listPurChased = db.getPurchaseProduct(mUserId);
		Log.i(TAG,"size purchase: " + listPurChased.size() );
		for (SaleTopic topic : listPurChased) {
			Log.i(TAG,"purchase: " + topic.getTopic() + " " + topic.getOfferPrice() );
		}
		db.close();
	}
	
	
	
	
	
	
}